package com.yzt.zhuju.dialog;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.R;
import com.yzt.zhuju.constants.IntentConstant;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.im.SendGiftEvent;
import com.yzt.zhuju.event.main.UmoneyNotEnoughEvent;
import com.yzt.zhuju.gift.GiftBatterManager;
import com.yzt.zhuju.gift.GiftManager;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.gift.Gift;
import com.yzt.zhuju.network.entity.gift.GiftBatterInfo;
import com.yzt.zhuju.network.entity.mine.wallet.WalletBean;
import com.yzt.zhuju.utils.ActivityManagerUtils;
import com.yzt.zhuju.utils.FastClickUtils;
import com.yzt.zhuju.utils.RechargeUtil;
import com.yzt.zhuju.widget.tuiview.TUITextView;
import com.yzt.p_base.utils.NetworkUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.plugin_widget.tableBar.SlidingTabLayout;
import com.yzt.plugin_widget.viewPager.ViewPagerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * author : bob
 * date   : 2022/12/5
 * desc   : 会话页面礼物弹窗
 */
public class ChatRoomGiftDialog extends BottomBaseDialog implements View.OnClickListener {

    // tab 组件
    private SlidingTabLayout slidingTabLayout;

    // 分页
    private ViewPager viewPager;

    // 我的钻石
    private TextView tvDiamond;

    // 发送按钮
    private TUITextView mSendButton;

    private Gift mGift;

    private String hisUid;

    /**
     * 送礼物场景 [ 1：私人，2：活动 ]
     */
    private int fromSource;

    private MyCountDownTimer countDownTimer;

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_conversation_gift;
    }

    @Override
    public int getGravity() {
        return Gravity.BOTTOM;
    }

    @Override
    public void bindView(View v) {

        Bundle arguments = getArguments();
        hisUid = arguments.getString(IntentConstant.INTENT_USER_ID);
        fromSource = arguments.getInt("extra_source", 1);
        if (TextUtils.isEmpty(hisUid)) {
            hisUid = "0";
        }

        slidingTabLayout = v.findViewById(R.id.sliding_tab_layout);
        viewPager = v.findViewById(R.id.view_pager);

        tvDiamond = v.findViewById(R.id.gift_footer_diamond);
        mSendButton = v.findViewById(R.id.gift_footer_send);

        mSendButton.setOnClickListener(this);
        findViewById(R.id.layout_recharge).setOnClickListener(this);
        tvDiamond.setOnClickListener(this);

        GiftManager.getInstance().getGiftListData();

        initData();

        // 初始化金币数量
        iniDiamondData();

        // 初始化礼物
        initGiftData();
    }

    public void initData() {
        int[] selectIndex = GiftManager.getInstance().getSelectUbiIndex();
        if (selectIndex[selectIndex.length - 1] == -1) {
            selectIndex[0] = 0;
            GiftManager.getInstance().setSelectUbiIndex(selectIndex);
        }
        GiftManager.getInstance().setSelectUbiTab(selectIndex.clone());
        GiftBatterManager.getInstance().initDiamond();
    }

    /**
     * 初始化礼物
     */
    private void initGiftData() {
        List<String> listTitle = new ArrayList<>();
        List<Fragment> mFragments = new ArrayList<>();
        listTitle.add("礼物");
        ChatRoomGiftItemFragment fragment = ChatRoomGiftItemFragment.newInstance(1, GiftManager.getInstance().getDiamondGiftList());
        fragment.setOnSelectGiftClickListener(new ChatRoomGiftItemFragment.OnSelectGiftClickListener() {
            @Override
            public void onSelect(int type, Gift gift) {
                ChatRoomGiftDialog.this.mGift = gift;
                int giftId = gift.getId();
                sendGift(giftId);
            }
        });
        mFragments.add(fragment);
        ViewPagerAdapter mViewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager(), mFragments, listTitle);
        viewPager.setAdapter(mViewPagerAdapter);
        viewPager.setOffscreenPageLimit(mFragments.size());
        slidingTabLayout.setViewPager(viewPager);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int[] selectIndex = GiftManager.getInstance().getSelectTab();
                selectIndex[1] = position;
                GiftManager.getInstance().setSelectTab(selectIndex);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.gift_footer_diamond || v.getId() == R.id.layout_recharge) {
            //充值
            RechargeUtil.toRecharge(getActivity(), false);
        } else if (v.getId() == R.id.gift_footer_send) {

            //发送
            if (FastClickUtils.isFastClick()) {
                return;
            }

            if (!NetworkUtils.isConnected()) {
                ToastUtil.showMessage(getString(R.string.rc_network_exception));
                return;
            }

            if (mGift == null) {
                ToastUtil.showMessage(getString(R.string.please_select_gift));
                return;
            }
            mGift.setTabId(1);
            mGift.setNum(1);
            double totalDiamond = GiftBatterManager.getInstance().getDiamondNum();
            if (totalDiamond < mGift.getWorth()) {
                FragmentActivity activity = ActivityManagerUtils.getInstance().getTopActivity();
                if (activity != null) {
                    ToastUtil.showMessage(getString(R.string.money_not_enough));
                    RechargeUtil.toRecharge(activity, false);
                }
                return;
            }

            JSONObject json = new JSONObject();
            json.put("giftId", mGift.getGiftId());
            json.put("scenarioType", fromSource);
            if (fromSource == 1) {
                json.put("userId", hisUid);
            } else {
                json.put("activityId", hisUid);
            }
            BizLayer.getInstance().getGiftModule().postSendGiftToOther(json, new AresSubscriber<Object>() {
                @Override
                protected void onSuccess(Object response) {
                    ToastUtil.showMessage("赠送成功！");
                    SendGiftEvent messageExtra = new SendGiftEvent();
                    messageExtra.setGiftIcon(mGift.getGiftIcon());
                    messageExtra.setCandyCoin(mGift.getCandyCoin());
                    messageExtra.setGiftName(mGift.getGiftName());
                    messageExtra.setGiftId(mGift.getGiftId() + "");
                    messageExtra.setTargetUid(hisUid);
                    messageExtra.setType(fromSource);
                    RxBus.getDefault().post(messageExtra);
                    iniDiamondData();
                }

                @Override
                protected void onError(int code, String info) {
                    super.onError(code, info);
                    if (code == 934) {
                        RxBus.getDefault().post(new UmoneyNotEnoughEvent());
                    }
                }
            });
        }
    }

    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if ((int) (millisUntilFinished / 1000) > 0) {
                mSendButton.setText(getString(R.string.double_click) + (int) (millisUntilFinished / 1000) + "s");
            }
        }

        @Override
        public void onFinish() {
            countDownTimer = null;
        }
    }

    /**
     * 初始化你的钻石
     */
    private void iniDiamondData() {
        BizLayer.getInstance().getMineModule().wallet(new AresSubscriber<WalletBean>() {
            @Override
            protected void onSuccess(WalletBean walletEntry) {
                tvDiamond.setText(walletEntry.getCandyNum() + "糖币");
            }
        });
    }

    private void sendGift(int giftId) {
        GiftBatterInfo giftBatterInfo = GiftBatterManager.getInstance().getTimeByGiftId(giftId);
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        if (giftBatterInfo != null) {
            mSendButton.setText(getString(R.string.double_click) + (int) (giftBatterInfo.getTime() / 1000) + "s");
            countDownTimer = new MyCountDownTimer(giftBatterInfo.getTime(), 1000);
            countDownTimer.start();
        } else {
            mSendButton.setText(getString(R.string.send_gift));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GiftManager.getInstance().setGiftCacheInfo(null);
    }
}